# -*- coding: utf-8 -*-
import hashlib
from datetime import datetime
import string
import os.path, random

COMMANDS = {
            'list': ('list', 'Displays a list of all the available files'),
            'get': ('get <remote filename>', 'Downloads a file with a given filename'),
            'put': ('put <local file path> <remote file name>', 'Uploads a file with a given filename'),
            'help': ('help', 'Displays a list of all the available commands'),
            'quit': ('quit', 'Disconnects from the server'),
}

def timestamp():
    """ Returns current time stamp. """
    return '[%s]'  % (datetime.strftime(datetime.now(), '%H:%M:%S'))

def display_message(message):
    """ Displays a message with a prepended time stamp. """
    
    print '%s %s' % (timestamp(), message)

def validate_file_md5_hash(file, original_hash):
    """ Returns true if file MD5 hash matches with the provided one, false otherwise. """

    if get_file_md5_hash(file) == original_hash:
        return True
        
    return False

def random_filename(length=16, prefix='', suffix='', verify=True, attempts=10, directory=""):
    letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m']
    letters += ['n','o','p','q','r','s','t','u','v','w','x','y','z']
    letters += ['A','B','C','D','E','F','G','H','I','J','K','L','M']
    letters += ['N','O','P','Q','R','S','T','U','V','W','X','Y']
    letters += ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
    for attempt in range(attempts):
        filename = ''.join([random.choice(letters) for i in range(length)])
        filename = prefix + filename + suffix
        if not verify or not os.path.exists( os.path.join(directory, filename) ):
            return filename


def get_file_md5_hash(file):
    """ Returns file MD5 hash"""
    
    md5_hash = hashlib.md5()
    for bytes in read_bytes_from_file(file):
        md5_hash.update(bytes)
        
    return md5_hash.hexdigest()

def read_bytes_from_file(file, chunk_size = 8100):
    """ Read bytes from a file in chunks. """
    
    with open(file, 'rb') as file:
        while True:
            chunk = file.read(chunk_size)
            
            if chunk:
                    yield chunk
            else:
                break
